package com.example.graduation.config.shiro;

import com.example.graduation.dto.UserDto;
import com.example.graduation.entity.User;
import com.example.graduation.service.UserService;
import com.example.graduation.util.JwtUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * ProjectName graduation
 *
 * @author xieyucan
 * <br>CreateDate 2022/2/14 10:49
 */
@Component
public class ShiroRealm extends AuthorizingRealm {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private UserService userService;


    /**
     * 希望他的token是我们期待的那个类型的token
     *
     * @param token
     * @return {@link boolean}
     * @author xieyucan
     * CreateDate 2022/2/14 10:58
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof ShiroToken;
    }


    /**
     * 授权
     *
     * @param principals
     * @return {@link AuthorizationInfo}
     * @author xieyucan
     * CreateDate 2022/2/14 10:57
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        UserDto userDto = (UserDto) principals.getPrimaryPrincipal();
        Integer userId = userDto.getId();
        Set<String> permissions = userService.searchPermissionById(userId);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permissions);
        return info;
    }


    /**
     * 认证
     *
     * @param token
     * @return {@link AuthenticationInfo}
     * @author xieyucan
     * CreateDate 2022/2/14 10:58
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();
        int userId = jwtUtil.getUserIdByToken(accessToken);
        User user = userService.searchById(userId);
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(user, userDto);
        if (userDto == null) {
            throw new LockedAccountException("账号已被锁定，请联系管理员");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userDto, accessToken, this.getName());
        return info;
    }
}
